#include "stockin.h"
#include <QFont>
#include <QLabel>
#include <QDoubleValidator>
#include <QDate>
#include <QWidget>
#include <QFrame> // 新增用于模拟阴影效果
#include <QSpacerItem> // 添加间隔项支持
#include <QStackedWidget>
#include "inventoryservice.h"
#include "userservice.h"
#include "appinitializer.h"
#include <QMessageBox>
#include <QDebug>

StockIn::StockIn(const QMap<QString, QVariant> &userInfo, QWidget *parent)
    : QWidget(parent), m_currentUser(userInfo)
{

    // 初始化服务层
    Database *db = AppInitializer::database();
    m_inventoryService = new InventoryService(db, this);
    m_userService = new UserService(db, this);

    initUI();
    setupStyles();

    connect(m_btnReturn, &QPushButton::clicked, this, &StockIn::onReturnClicked);
    connect(m_btnHistory, &QPushButton::clicked, this, &StockIn::onHistoryClicked);
    connect(m_btnSave, &QPushButton::clicked, this, &StockIn::onSaveClicked);
    connect(m_btnCancel, &QPushButton::clicked, this, &StockIn::onCancelClicked);

    // 连接分类和产品下拉框的信号
    connect(m_cmbCategory, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &StockIn::onCategoryChanged);
    connect(m_cmbProduct, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &StockIn::onProductChanged);

    // 加载分类
    loadCategories();

    // 设置操作员（这里需要根据实际登录用户设置）
        if (!m_currentUser.isEmpty()) {
            QString operatorName = m_currentUser["real_name"].toString();
            qDebug() << "Setting operator name:" << operatorName;
            m_edtOperator->setText(operatorName);
        } else {
            qDebug() << "No user info available";
            m_edtOperator->setText("未知操作员");
        }
}

StockIn::~StockIn()
{
    // Qt自动管理内存
}

void StockIn::initUI()
{
    setWindowTitle(tr("商品入库"));
    resize(800, 650);
    setAttribute(Qt::WA_StyledBackground, true);

    // 主布局
    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(20, 20, 20, 20);
    m_mainLayout->setSpacing(20);

    // 顶部按钮布局
    m_topButtonLayout = new QHBoxLayout();
    m_btnReturn = new QPushButton(tr("返回库存管理"));
    m_btnHistory = new QPushButton(tr("入库记录"));

    // 操作员标签和输入框
    QLabel *lblOperatorTitle = new QLabel(tr("操作员:"));
    m_edtOperator = new QLineEdit();
    m_edtOperator->setReadOnly(true);
    m_edtOperator->setFixedWidth(120); // 设置固定宽度
    m_edtOperator->setStyleSheet("color: #2D3436; background-color: rgba(245, 245, 245, 0.85);");

    m_topButtonLayout->addWidget(m_btnReturn);
    m_topButtonLayout->addWidget(m_btnHistory);
    m_topButtonLayout->addStretch();
    m_topButtonLayout->addWidget(lblOperatorTitle);
    m_topButtonLayout->addWidget(m_edtOperator);

    // 创建阴影容器
    m_shadowContainer = new QFrame(this);
    m_shadowContainer->setObjectName("shadowContainer");
    QVBoxLayout *shadowLayout = new QVBoxLayout(m_shadowContainer);
    shadowLayout->setContentsMargins(5, 5, 5, 5); // 为阴影留出空间

    // 表单容器
    m_formContainer = new QWidget(m_shadowContainer);
    m_formContainer->setObjectName("formContainer");
    QVBoxLayout *formContainerLayout = new QVBoxLayout(m_formContainer);
    formContainerLayout->setContentsMargins(30, 30, 30, 30);
    formContainerLayout->setSpacing(18);

    // 表单布局
    m_formLayout = new QGridLayout();
    m_formLayout->setSpacing(15);
    m_formLayout->setColumnStretch(1, 1);

    // 标题
    QLabel *lblTitle = new QLabel(tr("商品入库信息"));
    QFont titleFont = lblTitle->font();
    titleFont.setPointSize(16);
    titleFont.setBold(true);
    lblTitle->setFont(titleFont);
    m_formLayout->addWidget(lblTitle, 0, 0, 1, 2, Qt::AlignCenter);

    // 入库单号
    QLabel *lblInId = new QLabel(tr("入库单号:"));
    m_edtInId = new QLineEdit();
    m_edtInId->setReadOnly(true);
    m_edtInId->setPlaceholderText(tr("系统自动生成"));
    m_formLayout->addWidget(lblInId, 1, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_edtInId, 1, 1);

    // 商品分类
    QLabel *lblCategory = new QLabel(tr("商品分类:"));
    m_cmbCategory = new QComboBox();
    m_cmbCategory->addItem(tr("请选择分类"));
    m_cmbCategory->setItemData(0, QVariant(false), Qt::UserRole - 1);
    m_formLayout->addWidget(lblCategory, 2, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_cmbCategory, 2, 1);

    // 商品名称
    QLabel *lblProduct = new QLabel(tr("商品名称:"));
    m_cmbProduct = new QComboBox();
    m_cmbProduct->addItem(tr("请先选择分类"));
    m_cmbProduct->setItemData(0, QVariant(false), Qt::UserRole - 1);
    m_formLayout->addWidget(lblProduct, 3, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_cmbProduct, 3, 1);

    // 当前库存 (原商品ID)
    QLabel *lblCurrentStock = new QLabel(tr("当前库存:"));
    m_edtCurrentStock = new QLineEdit();
    m_edtCurrentStock->setReadOnly(true);
    m_formLayout->addWidget(lblCurrentStock, 4, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_edtCurrentStock, 4, 1);

    // 商品规格
    QLabel *lblSpecification = new QLabel(tr("商品规格:"));
    m_edtSpecification = new QLineEdit();
    m_edtSpecification->setReadOnly(true);
    m_formLayout->addWidget(lblSpecification, 5, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_edtSpecification, 5, 1);

    // 商品进价
    QLabel *lblPurchasePrice = new QLabel(tr("商品进价:"));
    m_edtPurchasePrice = new QLineEdit();
    m_edtPurchasePrice->setReadOnly(true);
    m_formLayout->addWidget(lblPurchasePrice, 6, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_edtPurchasePrice, 6, 1);

    // 供应商
    QLabel *lblSupplier = new QLabel(tr("供应商:"));
    m_edtSupplier = new QLineEdit();
    m_edtSupplier->setReadOnly(true);
    m_formLayout->addWidget(lblSupplier, 7, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_edtSupplier, 7, 1);

    // 入库数量
    QLabel *lblQuantity = new QLabel(tr("入库数量:"));
    m_edtQuantity = new QLineEdit();
    m_edtQuantity->setValidator(new QIntValidator(1, 9999, this));
    m_edtQuantity->setPlaceholderText(tr("请输入入库数量"));
    m_formLayout->addWidget(lblQuantity, 8, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_edtQuantity, 8, 1);

    // 入库日期
    QLabel *lblInDate = new QLabel(tr("入库日期:"));
    m_dateIn = new QDateEdit(QDate::currentDate());
    m_dateIn->setDisplayFormat("yyyy-MM-dd");
    m_dateIn->setCalendarPopup(true);
    m_formLayout->addWidget(lblInDate, 9, 0, Qt::AlignRight | Qt::AlignVCenter);
    m_formLayout->addWidget(m_dateIn, 9, 1);

    // 备注
    QLabel *lblNote = new QLabel(tr("备注:"));
    m_edtNote = new QTextEdit();
    m_edtNote->setMaximumHeight(80);
    m_edtNote->setPlaceholderText(tr("请输入备注信息（可选）"));
    m_formLayout->addWidget(lblNote, 10, 0, Qt::AlignRight | Qt::AlignTop);
    m_formLayout->addWidget(m_edtNote, 10, 1);

    // 底部按钮布局
    m_bottomButtonLayout = new QHBoxLayout();
    m_btnSave = new QPushButton(tr("确认入库"));
    m_btnCancel = new QPushButton(tr("取消"));

    m_bottomButtonLayout->addStretch();
    m_bottomButtonLayout->addWidget(m_btnSave);
    m_bottomButtonLayout->addSpacing(15);
    m_bottomButtonLayout->addWidget(m_btnCancel);
    m_bottomButtonLayout->addStretch();

    // 组装布局 - 关键修改：添加垂直间隔项
    formContainerLayout->addLayout(m_formLayout);
    // 添加一个垂直间隔项，将按钮推到底部
    formContainerLayout->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding));
    formContainerLayout->addLayout(m_bottomButtonLayout);

    shadowLayout->addWidget(m_formContainer);
    m_mainLayout->addLayout(m_topButtonLayout);
    m_mainLayout->addWidget(m_shadowContainer, 0, Qt::AlignCenter);

    // Tab顺序
    setTabOrder(m_cmbCategory, m_cmbProduct);
    setTabOrder(m_cmbProduct, m_edtQuantity);
    setTabOrder(m_edtQuantity, m_dateIn);
    setTabOrder(m_dateIn, m_edtNote);
    setTabOrder(m_edtNote, m_btnSave);
    setTabOrder(m_btnSave, m_btnCancel);
}

void StockIn::setupStyles()
{
    QString styleSheet = R"(
        StockIn {
            background: qlineargradient(
                x1: 0, y1: 0, x2: 0, y2: 1,
                stop: 0 #E8F5E9,
                stop: 0.5 #C8E6C9,
                stop: 1 #A5D6A7
            );
        }

        #shadowContainer {
            background-color: rgba(0, 0, 0, 0.1);
            border-radius: 12px;
            max-width: 510px; /* 比表单容器宽10px，为阴影留出空间 */
        }

        #formContainer {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 10px;
            max-width: 500px;
            min-height: 550px; /* 确保表单容器有足够的高度 */
        }

        QLabel {
            color: #2D3436;
            font-size: 13px;
            font-family: "Microsoft YaHei", sans-serif;
        }

        QLineEdit, QComboBox, QDateEdit, QTextEdit {
            color: #2D3436;
            background-color: rgba(255, 255, 255, 0.85);
            border: 1px solid #C8E6C9;
            border-radius: 6px;
            padding: 6px 12px;
            font-size: 13px;
            font-family: "Microsoft YaHei", sans-serif;
        }

        QLineEdit:focus, QComboBox:focus, QDateEdit:focus, QTextEdit:focus {
            border: 1px solid #4CAF50;
            /* 移除box-shadow，改为边框发光效果 */
            border-color: #4CAF50;
            outline: none;
        }

        QLineEdit:read-only, QComboBox:read-only {
            background-color: rgba(245, 245, 245, 0.85);
            color: #636E72;
        }

        /* 左上角按钮样式 - 浅蓝色 */
        QPushButton#btnReturn, QPushButton#btnHistory {
            background-color: #81D4FA;
            color: #01579B;
            border: none;
            border-radius: 6px;
            padding: 8px 18px;
            font-size: 13px;
            font-family: "Microsoft YaHei", sans-serif;
            font-weight: 500;
        }

        QPushButton#btnReturn:hover, QPushButton#btnHistory:hover {
            background-color: #4FC3F7;
            border: 1px solid rgba(129, 212, 250, 0.3);
        }

        QPushButton#btnReturn:pressed, QPushButton#btnHistory:pressed {
            background-color: #29B6F6;
        }

        /* 底部按钮样式 - 浅绿色 */
        QPushButton#btnSave, QPushButton#btnCancel {
            background-color: #A5D6A7;
            color: #2E7D32;
            border: none;
            border-radius: 6px;
            padding: 8px 18px;
            font-size: 13px;
            font-family: "Microsoft YaHei", sans-serif;
            font-weight: 500;
        }

        QPushButton#btnSave:hover, QPushButton#btnCancel:hover {
            background-color: #81C784;
            border: 1px solid rgba(165, 214, 167, 0.3);
        }

        QPushButton#btnSave:pressed, QPushButton#btnCancel:pressed {
            background-color: #66BB6A;
        }

        /* 默认按钮样式（备用） */
        QPushButton {
            background-color: #E0E0E0;
            color: #424242;
            border: none;
            border-radius: 6px;
            padding: 8px 18px;
            font-size: 13px;
            font-family: "Microsoft YaHei", sans-serif;
            font-weight: 500;
        }

        QTextEdit {
            min-height: 80px;
            line-height: 1.5;
        }

        /* 下拉框提示项样式 */
        QComboBox::item:index(0) {
            color: #999999;
        }
    )";

    // 为按钮设置对象名称以便样式表选择
    m_btnReturn->setObjectName("btnReturn");
    m_btnHistory->setObjectName("btnHistory");
    m_btnSave->setObjectName("btnSave");
    m_btnCancel->setObjectName("btnCancel");

    setStyleSheet(styleSheet);
}

// 槽函数空实现
void StockIn::onReturnClicked() {}
void StockIn::onRefreshClicked() {}

void StockIn::onHistoryClicked() 
{
    // 获取父级IM窗口并切换到入库统计页面
    QWidget *parent = this->parentWidget();
    while (parent && !qobject_cast<QStackedWidget*>(parent)) {
        parent = parent->parentWidget();
    }
    
    if (QStackedWidget *stackedWidget = qobject_cast<QStackedWidget*>(parent)) {
        // 切换到入库统计页面（索引3，第四个页面）
        stackedWidget->setCurrentIndex(3);
    }
}

void StockIn::onSaveClicked()
{
    // 验证输入
    if (m_cmbCategory->currentIndex() <= 0) {
        QMessageBox::warning(this, tr("警告"), tr("请选择商品分类"));
        return;
    }

    if (m_cmbProduct->currentIndex() <= 0) {
        QMessageBox::warning(this, tr("警告"), tr("请选择商品"));
        return;
    }

    int quantity = m_edtQuantity->text().toInt();
    if (quantity <= 0) {
        QMessageBox::warning(this, tr("警告"), tr("请输入有效的入库数量"));
        return;
    }

    // 获取选中的产品ID
    int productId = m_cmbProduct->currentData().toInt();
    double purchasePrice = m_edtPurchasePrice->text().toDouble();
    QString supplier = m_edtSupplier->text();
    QString note = m_edtNote->toPlainText();

    // 获取操作员ID（这里需要根据实际登录用户获取）
    int operatorId = 1; // 假设操作员ID为1

    // 执行入库操作
    bool success = m_inventoryService->stockIn(productId, quantity, purchasePrice,
                                             supplier, operatorId, note);

    if (success) {
        QMessageBox::information(this, tr("成功"), tr("商品入库成功"));
        onCancelClicked(); // 清空表单
    } else {
        QMessageBox::critical(this, tr("错误"), tr("商品入库失败，请重试"));
    }
}

void StockIn::onCancelClicked()
{
    m_cmbCategory->setCurrentIndex(0);
    m_cmbProduct->clear();
    m_cmbProduct->addItem(tr("请先选择分类"));
    clearForm();
}

// 添加新的槽函数
void StockIn::onCategoryChanged(int index)
{
    if (index > 0) { // 跳过"请选择分类"
        int categoryId = m_cmbCategory->currentData().toInt();
        loadProductsByCategory(categoryId);
    } else {
        m_cmbProduct->clear();
        m_cmbProduct->addItem(tr("请先选择分类"));
        clearForm();
    }
}

void StockIn::onProductChanged(int index)
{
    if (index > 0) { // 跳过"请选择商品"
        int productId = m_cmbProduct->currentData().toInt();
        updateProductInfo(productId);
    } else {
        clearForm();
    }
}

// 实现新的私有方法
void StockIn::loadCategories()
{
    m_cmbCategory->clear();
    m_cmbCategory->addItem(tr("请选择分类"), -1);

    auto categories = m_inventoryService->getAllCategories();
    for (const auto &category : categories) {
        m_cmbCategory->addItem(category["category_name"].toString(),
                              category["category_id"]);
    }
}

void StockIn::loadProductsByCategory(int categoryId)
{
    m_cmbProduct->clear();
    m_cmbProduct->addItem(tr("请选择商品"), -1);

    auto products = m_inventoryService->getProductsByCategory(categoryId);
    for (const auto &product : products) {
        m_cmbProduct->addItem(product["product_name"].toString(),
                             product["product_id"]);
    }
}

void StockIn::updateProductInfo(int productId)
{
    auto product = m_inventoryService->getProductDetails(productId);
    if (product.isEmpty()) {
        clearForm();
        return;
    }

    int currentStock = m_inventoryService->getCurrentStock(productId);

    m_edtCurrentStock->setText(QString::number(currentStock));
    m_edtSpecification->setText(product["specification"].toString());
    m_edtPurchasePrice->setText(QString::number(product["purchase_price"].toDouble()));
    m_edtSupplier->setText(product["supplier"].toString());
}

void StockIn::clearForm()
{
    m_edtCurrentStock->clear();
    m_edtSpecification->clear();
    m_edtPurchasePrice->clear();
    m_edtSupplier->clear();
    m_edtQuantity->clear();
    m_edtNote->clear();
}

